package pers.cz.thread;

import org.apache.ibatis.session.SqlSession;
import pers.cz.session.ContextHolder;

import java.util.Map;
import java.util.Queue;

/**
 * @program: PostGirl-panent
 * @description: Master-Worker模式：Worker主要用于任务执行
 * @author: Cheng Zhi
 * @create: 2022-05-03 22:18
 **/
public class Worker implements Runnable {

    // 子任务队列
    protected Queue<Object> workQueue;
    // 结果集
    protected Map<String, Object> resultMap;
    // 分表编号
    protected Queue<Integer> shardingQueue;

    public void setWorkQueue(Queue workQueue) {
        this.workQueue = workQueue;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    public void setShardingQueue(Queue shardingQueue) {
        this.shardingQueue = shardingQueue;
    }
    /**
     * 子任务处理逻辑，供子类实现并处理
     * @param input
     * @return
     */
    public Map<SqlSession, Object> handle(Object input) {

        return (Map<SqlSession, Object>) new Object();
    }
    @Override
    public void run() {
        while (true) {

            Object input = workQueue.poll();
            if (input == null) {
                // 任务全部执行完成则退出
                break;
            }
            ContextHolder.initContext();
            Integer shardingNum = shardingQueue.poll();
            // 通过线程遍历来设置分表
            ContextHolder.getRequestContext().put("SO_NBR", shardingNum);
            // 处理子任务
            Object result = handle(input);
            // 将处理结果写入结果集
            resultMap.put(Integer.toString(shardingNum.hashCode()),result);
            ContextHolder.getRequestContext().remove("SO_NBR");
        }
    }
}
